function latex_table(texfile,res,align,num_hline)
% gen_latex_table: Generate a latex file from a table in MATLAB
%
% SYNTAX:
%   gen_latex_table(texfile,res,align,num_hline)
%   Save the table stored in res to a latex file texfile (tabular environment).
%   Filename texfile specifies the file to write (overwrite).
%   Table res should be a cell holding the entries in each row and column.
%   String align (optional) specifies the align format string of LaTeX table.
%   Integer num_hline (optional) specifies how many horizontal lines should be drawn.

%   Author: Hongbin Ma
%   Last updated: 2009-6-2 with MATLAB 6.5
%   Problems or suggestions? Email me: mathmhb[at]163.com

if nargin<4,
    hlines=length(res)+1;
else,
    hlines=num_hline;
end;
if nargin<3,
    s_align=['|',repmat('c|',1,length(res{1}))];
else,
    s_align=align;
end;

disp(['Writing ',texfile,' ...']);
fh=fopen(texfile,'w');
header=sprintf('\\begin{tabular}{%s}',s_align);
fprintf(fh,'%s\n',header);

if hlines>0,
    fprintf(fh,'%s\n','\hline');
end;
s_hline='';

for j=1:length(res),
    if j<hlines,
        s_hline=' \hline';
    end;
    for k=1:length(res{j}),
        d=res{j}{k};s='';sep=' & ';
        switch class(d)
        case 'double'
            s=sprintf('$%g$',d);
        case 'char'
            s=d;
        end;
        if k==length(res{j}),
            sep=['\\',s_hline];
        end;
        fprintf(fh,'%s %s\n',s,sep);
    end;
end;
tail='\end{tabular}';
fprintf(fh,'%s\n',tail);
fclose(fh);

disp('Writing finished.');
